﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Dunnice.BlogIndex.Entity;
using System.ComponentModel;
using Dunnice.BlogIndex.BLL;
using Dunnice.BlogIndex.BLL.LocalSiteStorage;
using Dunnice.Utility;
using System.Collections.ObjectModel;

namespace BlogIndexShow
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 工作类型.
        /// </summary>
        enum WorkType
        {
            DownloadArticle,
            CreateHtml
        }

        /// <summary>
        /// 所有作者信息.
        /// </summary>
        List<BlogAuthorInfo> _allAuthors;

        /// <summary>
        /// 需要下载的文章列表.
        /// </summary>
        List<BlogAuthorInfo> _targetAuthors;

        /// <summary>
        /// 后台工作线程.
        /// </summary>
        BackgroundWorker _bgWorker;

        /// <summary>
        /// 当前工作类型.
        /// </summary>
        WorkType _workType;

        ObservableCollection<BlogArticleInfo> _ArticleList = new ObservableCollection<BlogArticleInfo>();

        public MainWindow()
        {
            //this.listBoxArticle.ItemsSource = _ArticleList;

            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);

            _bgWorker = new BackgroundWorker();
            _bgWorker.DoWork += new DoWorkEventHandler(_bgWorker_DoWork);
            _bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgWorker_RunWorkerCompleted);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            BindBlogServer();

            RefreshBlogAuthorInfo();
        }

        private void _bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_workType == WorkType.DownloadArticle)
            {
                this.textblockStatus.Text = "下载文章完成";
                this.menuItemDownload.IsEnabled = true;
            }
            else if (_workType == WorkType.CreateHtml)
            {
                this.menuItemCreateHtml.IsEnabled = true;
            }
        }

        private void _bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            switch (_workType)
            {
                case WorkType.DownloadArticle:
                    SimultaneousDelegateControl<BlogAuthorInfo> downControl = new SimultaneousDelegateControl<BlogAuthorInfo>(
                        1, _targetAuthors, DownloadBlogArticle, string.Empty);

                    downControl.Start();
                    downControl.WaitToHandleComplated();
                    break;

                case WorkType.CreateHtml:
                    SimultaneousDelegateControl<BlogAuthorInfo> createHtmlControl = new SimultaneousDelegateControl<BlogAuthorInfo>(
                      1, _targetAuthors, CreateHtml, string.Empty);

                    createHtmlControl.Start();
                    createHtmlControl.WaitToHandleComplated();

                    var serverNames = _targetAuthors.Select(c => c.ServerName).Distinct();
                    foreach (string name in serverNames)
                    {
                        LocalSiteMaker.CreateAuthorIndex(name);
                    }

                    break;
            }
        }

        /// <summary>
        /// 添加博客作者.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonAddAuthor_Click(object sender, RoutedEventArgs e)
        {
            if (this.cbBlogServer.SelectedIndex < 0 || this.textBoxBlogUser.Text.Trim() == string.Empty)
                return;

            BlogServerInfo bsInfo = (this.cbBlogServer.ItemsSource as List<BlogServerInfo>)[this.cbBlogServer.SelectedIndex];

            BlogAuthorInfo author = new BlogAuthorInfo()
            {
                AuthorName = this.textBoxBlogUser.Text.Trim(),
                ServerName = bsInfo.EnumValue,
                BlogUrl = BlogBizControl.FormatBlogUrl(bsInfo, this.textBoxBlogUser.Text.Trim()),
                Alias = this.textBoxAlias.Text.Trim()
            };

            BlogBizControl.SaveBlogAuthorInfo(author);

            RefreshBlogAuthorInfo();
        }

        /// <summary>
        /// 下载文章.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuBackBlog_Click(object sender, RoutedEventArgs e)
        {
            MenuAction(sender, WorkType.DownloadArticle);
        }

        /// <summary>
        /// 创建Html.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuCreateHtml_Click(object sender, RoutedEventArgs e)
        {
            MenuAction(sender, WorkType.CreateHtml);
        }

        private void MenuAction(object sender, WorkType work)
        {
            (sender as UIElement).IsEnabled = false;

            object tag = null;

            if (this.treeViewAuthor.SelectedItem != null)
            {
                tag = (this.treeViewAuthor.SelectedItem as TreeViewItem).Tag;
            }

            if (tag == null)
            {
                _targetAuthors = _allAuthors;
            }
            else if (tag is BlogGroup)
            {
                _targetAuthors = _allAuthors.Where(c => c.GroupId.Value == (tag as BlogGroup).Id).ToList();
            }
            else if (tag is BlogAuthorInfo)
            {
                _targetAuthors = new List<BlogAuthorInfo>() { tag as BlogAuthorInfo };
            }

            this._workType = work;
            this._bgWorker.RunWorkerAsync();
        }

        /// <summary>
        /// 下载文章.
        /// </summary>
        /// <param name="author"></param>
        private void DownloadBlogArticle(BlogAuthorInfo author)
        {
            IBlogParser downloader = BlogParserFactory.CreateDownloader(author.ServerType);
            List<BlogArticleInfo> lstArticleInfo = downloader.GetArticleItems(author.AuthorName);

            AddMsg(string.Format("{0}共有文章{1} 篇.", author.AuthorName, lstArticleInfo.Count));

            List<BlogArticleInfo> lstExistArticle = BlogBizControl.GetArticleInfos(author);

            lstArticleInfo.Except(lstExistArticle, new BlogArticleInfo());

            AddMsg(string.Format("{0}还有{1}篇文章需要下载.", author.AuthorName, lstArticleInfo.Count));

            foreach (BlogArticleInfo article in lstArticleInfo)
            {
                AddMsg(string.Format("正在下载文章:{0}....", article.Title));

                article.ServerName = author.ServerName;
                article.AuthorName = author.AuthorName;
                article.Content = downloader.ParseArticleContent(article);

                BlogBizControl.SaveArticleInfo(article);

                AddMsg(string.Format("文章:{0}下载完成.", article.Title));
            }

            AddMsg(string.Format("{0}文章下载完成.", author.AuthorName));
        }

        private void CreateHtml(BlogAuthorInfo author)
        {
            LocalSiteMaker.CreateAuthorSite(author);
        }

        /// <summary>
        /// 添加消息.
        /// </summary>
        /// <param name="msg"></param>
        private void AddMsg(string msg)
        {
            Action<string> ac = delegate(string meg)
            {
                this.outputWindow.AppendText(meg);
                this.outputWindow.AppendText("\n");
                this.outputWindow.ScrollToEnd();
            };

            string message = string.Format("{0}: {1}", DateTime.Now.ToString(), msg);
            this.Dispatcher.BeginInvoke(ac, message);
        }

        /// <summary>
        /// 刷新作者信息.
        /// </summary>
        private void RefreshBlogAuthorInfo()
        {
            _allAuthors = BlogBizControl.GetBlogAuthorInfos();

            this.treeViewAuthor.Items.Clear();

            var g = from c in _allAuthors
                    group c by new BlogGroup(c.GroupId.Value, c.GroupName);

            foreach (var tmp in g)
            {
                TreeViewItem groupTitem = new TreeViewItem();
                groupTitem.Header = tmp.Key.Name;
                groupTitem.Tag = tmp.Key;
                groupTitem.IsExpanded = true;

                this.treeViewAuthor.Items.Add(groupTitem);

                foreach (BlogAuthorInfo author in tmp)
                {
                    TreeViewItem authorTitem = new TreeViewItem();
                    authorTitem.Header = author.GetAuthorShowName();
                    authorTitem.Tag = author;
                    authorTitem.Selected += new RoutedEventHandler(authorTitem_Selected);

                    groupTitem.Items.Add(authorTitem);
                }
            }
        }

        void authorTitem_Selected(object sender, RoutedEventArgs e)
        {
            List<BlogArticleInfo> article = BlogBizControl.GetArticleInfos((sender as TreeViewItem).Tag as BlogAuthorInfo);

            _ArticleList.Clear();
            article.ForEach(delegate(BlogArticleInfo art) { _ArticleList.Add(art); });
        }

        /// <summary>
        /// 绑定博客服务器列表.
        /// </summary>
        private void BindBlogServer()
        {
            List<BlogServerInfo> lstBs = BlogBizControl.GetBlogServerInfos();
            this.cbBlogServer.ItemsSource = lstBs;
            this.cbBlogServer.DisplayMemberPath = "ServerDesc";
            this.cbBlogServer.SelectedValuePath = "EnumValue";
            this.cbBlogServer.SelectedIndex = 0;
        }
    }
}
